home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 2950 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.8 KB

  1. Path: castle.nando.net!news
  2. From: actuary@nando.net   (Bill McCarthy)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: why get 9 strings only?
  5. Date: 25 Jan 1996 03:23:22 GMT
  6. Organization: News & Observer Public Access
  7. Message-ID: <4e6t3a$mii@castle.nando.net>
  8. References: <4e51th$4bi@news.nevada.edu>
  9. Reply-To: actuary@nando.net (Bill McCarthy)
  10. NNTP-Posting-Host: 152.52.37.91
  11. X-Newsreader: IBM NewsReader/2 v1.2
  12.  
  13. In <4e51th$4bi@news.nevada.edu>,
  14. chancl@nevada.edu (Clapton Chan) writes:
  15.  
  16. >I can't figure out why I can only input 9 strings
  17. >instead of 10 on the following program:
  18. >
  19. >**************************************************************
  20. >
  21. >/* Write a program that reads a number and then a list of  */
  22. >/* strings (all on separate lines), and then prints one of */ 
  23. >/* the lines from the list as selected by the number.      */
  24. >
  25. >#include <stdio.h>
  26. >
  27. >void main()
  28.  
  29. Make it C.  Use int main( void )
  30.  
  31. >{
  32. >    char str[10][80];
  33. >    int i, j;
  34. >
  35. >    printf("Enter a number (0-9):\n");
  36. >    scanf("%d", &j);
  37.  
  38. You're not eating the '\n' and anything typed between the int and
  39. the '\n'.  So, the first gets() is picking up everything after the int
  40. through the '\n'.  I would recommend against using scanf() or gets().
  41. But if you insist, replace the above scanf() with these two lines:
  42.  
  43.     scanf( "%d%*[^\n]", &j );
  44.     scanf( "%*c" );
  45.  
  46. >    printf("Enter 10 strings:\n");
  47. >    for(i=0; i<10; i++)         /* get 10 strings */
  48. >        gets(str[i]);        /* but can input 9 strings */
  49.  
  50. Now you'll be prompted (with no prompt) for 10 strings.
  51.  
  52. >    if(j>0 && j<10)
  53. >        printf("Answer: %s\n", str[j]);
  54.  
  55. Here's another problem.  This will only print the answer if
  56. j = 1 to 9 inclusive.  The valid input of 0 will be skipped.  Use:
  57.  
  58.     if ( j >= 0 && j < 10 )
  59.         printf( "Answer: %s", str[j] );
  60.  
  61. and don't forget to add:
  62.  
  63.     return 0;
  64.  
  65. >}
  66.  
  67. Bill McCarthy
  68. actuary@nando.net
  69. Wendell, NC  USA
  70.  
  71.